package org.pms.servlet;

import com.google.gson.Gson;
import org.pms.dao.ProductDao;
import org.pms.dao.impl.ProductDaoImpl;
import org.pms.dto.ResultDto;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 修改商品数量
 */
@WebServlet("/api/product_update_count.do")
public class UpdateProductCountServlet extends BaseServlet {
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.获取客户端传递的参数数据
        Map<String, String> map = parseMap(req);
        String id = map.get("pid");
        int count = Integer.parseInt(map.get("pcount"));

        // 2. 对数据进行处理（格式） -- 先封装到DTO对象中，后再序列为JSON字符串
        ProductDao productDao = new ProductDaoImpl();
        int row = productDao.updateCount(id, count);

        // 3.响应数据到客户端浏览器中
        ResultDto dto =successJson() ;
        if(row!=1) {
            dto = errorJson("修改数量失败") ;
        }
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.print(new Gson().toJson(dto));
        out.flush();
        out.close();
    }
}
